package sam.learn.biz.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import sam.learn.biz.user.repo.entity.UserInfo;
import sam.learn.biz.user.repo.mapper.UserInfoMapper;
import sam.learn.biz.user.service.UserInfoService;

import java.util.Objects;

@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private CacheManager cacheManager;

    @Override
    public UserInfo addUserInfo(String username, String password, String nickName, String regionCode) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String passHash = encoder.encode(password);
        UserInfo userInfo = UserInfo.create(username, passHash, nickName, regionCode);
        userInfoMapper.insert(userInfo);
        return userInfo;
    }

    @Override
    public UserInfo queryUserInfoBy(String username) {
        Cache cache = cacheManager.getCache("user-center:user-info");
        UserInfo userInfo = cache.get(username, UserInfo.class);
        if (Objects.nonNull(userInfo)) {
            return userInfo;
        } else {
            userInfo = doQueryUserInfoBy(username);
            cache.put(username, userInfo);
            return userInfo;
        }
    }

    private UserInfo doQueryUserInfoBy(String username) {
        LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>(UserInfo.class);
        lambdaQueryWrapper.eq(UserInfo::getUsername, username);
        return userInfoMapper.selectOne(lambdaQueryWrapper);
    }
}
